package com.liang.config;

import com.liang.common.components.JwtAuthorizationTokenFilter;
import com.liang.common.handler.JwtAuthenticationEntryPoint;
import com.liang.common.handler.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    JwtAuthorizationTokenFilter authenticationTokenFilter;

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //关闭csrf跨站请求防护
        http.csrf().disable();

        //前后端分离采用JWT 不需要session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 添加token过滤器
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        http.authorizeRequests()
                //不需要被认证的请求
                .antMatchers("/user/login", "/user/regist", "/druid/**","/static/**", "/chat", "/news/**").permitAll()
                .antMatchers(HttpMethod.GET, "/active/**", "/blog/**", "/file/**", "/cyun/source/**", "/user/exce").permitAll()
                .antMatchers(HttpMethod.PUT, "/blog/look/**").permitAll()
                .antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui",
                        "/swagger-resources", "/swagger-resources/configuration/security",
                        "/swagger-ui.html", "/webjars/**").permitAll()
                //解决跨域问题。cors 预检请求放行,让Spring security 放行所有preflight request（cors 预检请求）
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                //所有请求必须被认证，必须登陆之后才能被访问
                .anyRequest().authenticated();

        //异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(myAccessDeniedHandler);

//        //记住我
//        http.rememberMe()
//                //设置失效时间
//                .tokenValiditySeconds(60)
//                //自定义登录逻辑
//                .userDetailsService(userDetailsService);
    }


    /**
     * @Author 李昂
     * @Description 角色继承
     * @Date 2020/12/3 18:26
     */
    @Bean
    RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
        String hierarchy = "ROLE_admin > ROLE_normal";
        roleHierarchy.setHierarchy(hierarchy);
        return roleHierarchy;
    }
}
